<?php
class ControllerGrabLogingrab extends Controller {
	public function index() {
		$this->load->model('grab/logingrab');

		//抓取用户个人信息数据
		$msg = $this->weiboclient->verify_credentials();

		$query = $this->model_grab_logingrab->getVerifyById($msg['id']);
		$num = $query->num_rows;
		$data = array ();
		$data['name'] = $msg['name'];
		$data['id'] = $msg['id'];
		$data['location'] = $msg['location'];
		$data['description'] = $msg['description'];
		$data['created_at'] = $msg['created_at'];
		$data['followers_count'] = $msg['followers_count'];
		$data['friends_count'] = $msg['friends_count'];
		$data['gender'] = $msg['gender'];
		$data['statuses_count'] = $msg['statuses_count'];

		if ($num == 0) {
			$this->model_grab_logingrab->insert($data);
			$ids=$this->grablatesttweet($msg);
		} else
			if ($num == 1) {
				$this->model_grab_logingrab->update($data);
			}

		$weibo_influnce = $this->weiboclient->get_count_info_by_ids("3.3628998797931E+15,3.3628998797931E+15");
		Util::debug($weibo_influnce);
//		if (count($weibo_influnce) > 0) {
//			$this->model_grab_logingrab->update_tweet($weibo_influnce);
//		}
		$data = array ();
		$data['user_id'] = $msg['id'];
		$asyntask = new AsynTask('analyze/usertimeline', $data);
		$asyntask->execute();

		$taskdp = 'success to grab a login user data.';
		$this->response->setOutput($this->render($taskdp));
	}

	//抓取用户最近两百条微博
	public function grablatesttweet($msg) {
		$user_id = $msg['id'];

		$weibomsg = $this->weiboclient->user_timeline(1, 200, $user_id);

		if (!isset ($weibomsg)) {
			$this->log->write('$weibomsg is not set.');
		}
		if ($weibomsg == null || $weibomsg == false || $weibomsg == '') {
			$this->log->write('$weibomsg=null||$weibomsg==false||$weibomsg=nothing');
		}
		if (isset ($weibomsg['error_code'])) {
			$this->log->write($weibomsg['error']);
		}

		$i = 0;
		$ids = '';

		foreach ($weibomsg as $weibo_data) {

			$insert_data = array ();
			$insert_data['user_id'] = $user_id;
			$insert_data['text'] = $weibo_data['text'];
			$insert_data['id'] = $weibo_data['id'];
			$insert_data['created_at'] = $weibo_data['created_at'];
			$insert_data['is_retweet'] = isset ($weibo_data['retweeted_status']);
			if (isset ($weibo_data['retweeted_status'])) {
				$insert_data['retweet_id'] = $weibo_data['retweeted_status']['id'];
			}
			if ($i == 0) {
				$ids = $weibo_data['id'];
			} else {
				$ids .= ',' . $weibo_data['id'];
			}
			$i++;

			$this->model_grab_logingrab->insert_tweet($insert_data);
		}
		return $ids;
	}
}
?>